import { addOneCoupons } from '@/services/coupons';
import { Button, DatePicker, Form, Input, message, Modal, Select } from 'antd';
import moment from 'moment';
import styles from '../index.less';

type Props = {
  visible: boolean;
  handleCancel: () => void;
  getList: () => void;
};

const CreateNew: React.FC<Props> = ({ visible, handleCancel, getList }) => {
  //   const qs = getQueryParams();
  const [form] = Form.useForm();
  const { Option } = Select;
  const { RangePicker } = DatePicker;
  const colorThem = localStorage.getItem('color') || '#1a7721';

  // 初始值
  const getInitValues = () => {
    return {
      efforts: '200',
    };
  };

  //  优惠券区间仅能从今日以及今日之前开始
  const disabledDate = (current: any) => {
    return current < moment().startOf('day');
  };

  const confirmSubmit = async (values: any) => {
    try {
      await addOneCoupons(values).then(() => {
        message.success('新建优惠券成功！');
        getList();
      });
      handleCancel();
      form.setFieldsValue({ date: [], efforts: '200', name: '' });
    } catch (error) {
      console.log(error);
    }
  };

  const onFinish = async () => {
    let values = await form.validateFields();
    values.timeStart = new Date(values.date[0]).getTime();
    values.timeEnd = new Date(values.date[1]).getTime();

    Modal.confirm({
      title: '新建',
      centered: true,
      content: '是否新建该优惠券？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => confirmSubmit(values),
    });
  };

  return (
    <Modal
      visible={visible}
      footer={[
        <>
          <Button
            onClick={() => {
              handleCancel();
              form.setFieldsValue({ date: [], efforts: '200', name: '' });
            }}
            className={styles.btnCancel}
          >
            取消
          </Button>
          <Button
            className={styles.btnSeal}
            style={{ background: `${colorThem}`, width: 120, color: '#fff' }}
            htmlType="submit"
            type="primary"
            onClick={onFinish}
          >
            新建
          </Button>
        </>,
      ]}
      closable={false}
      className={styles.modalsStyle}
      width={540}
      title={'新建优惠券'}
      centered={true}
    >
      <div className={styles.modalContent}>
        <Form
          className={styles?.formStyle}
          onFinish={onFinish}
          form={form}
          initialValues={getInitValues()}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 28 }}
        >
          <Form.Item
            label="活动名称"
            name="name"
            validateTrigger="onBlur"
            rules={[
              {
                required: true,
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请输入活动名称
                  </div>
                ),
              },
              {
                pattern: new RegExp(/^[\u4e00-\u9fa5_a-zA-Z0-9]{4,10}$/),
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请输入4-10个字符（包括中文，英文字母和数字及下划线）
                  </div>
                ),
              },
            ]}
          >
            <Input placeholder="请输入活动名称" autoComplete="off" />
          </Form.Item>
          <Form.Item
            label="优惠力度"
            name="efforts"
            rules={[
              {
                required: true,
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请选择优惠力度
                  </div>
                ),
              },
            ]}
          >
            <Select placeholder="请选择优惠力度">
              <Option value="200">满200-20</Option>
              <Option value="300">满300-40</Option>
              <Option value="500">满500-70</Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="起止日期"
            name="date"
            rules={[
              {
                required: true,
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请选择起止日期
                  </div>
                ),
              },
            ]}
          >
            <RangePicker showTime disabledDate={disabledDate} />
          </Form.Item>
        </Form>
      </div>
    </Modal>
  );
};

export default CreateNew;
